import fetch from "node-fetch";
import path from 'path';
import fs from 'fs';
import lodash from 'lodash';

const tips = [
    '绑定信息不完整，请检查账号和密码绑定。',
    '请先绑定账号和密码。'
]

const dataStorageDirectory = 'data/Jiaozi/shuabu'
fs.mkdirSync(dataStorageDirectory, { recursive: true });

const regular = [
    /^(#|\/)?绑定zepp账号(\S+)$/,
    /^(#|\/)?绑定zepp密码(\S+)$/,
    /^(#|\/)?(微信刷步|修改步数|刷步)(\d+)$/,
    /^(#|\/)?(随机刷步|随机步数)(\d+)$/
]
export class example extends plugin {
    constructor() {
        super({
            name: '刷步数',
            dsc: '刷取微信步数，占领步数排行榜',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^(#|\/)?(刷步帮助|(怎么|咋)刷步)$/, fnc: 'help' },
                { reg: regular[0], fnc: 'bindAccount' },
                { reg: regular[1], fnc: 'bindPassword' },
                { reg: regular[2], fnc: 'sb' },
                { reg: regular[3], fnc: 'sjsb' },
                { reg: /^(#|\/)?查看zepp绑定$/, fnc: 'viewBindingInfo' },
            ]
        });
    }

    async help(e) {
        const helpText = [
            '——⭐刷步帮助⭐——',
            '\r发送 "#绑定zepp账号123456789"绑定账号',
            '\r发送 "#绑定zepp密码123456789"绑定密码',
            '\r发送 "#刷步11451"进行刷步',
            '\r发送 "#随机刷步11451"进行随机刷步 11451步以内',
            '\r帮助文档:https://pd.qq.com/s/7g6rt3g02'
        ]
        return e.reply(helpText.join(''))
    }

    async bindAccount(e) {
        try {
            const [, , account] = e.msg.match(regular[0]);
            if (!account) return e.reply('请提供有效的账号。')
            const FILE_PATH = path.join(dataStorageDirectory, `${e.user_id}.json`);
            let userData = {};
            if (AAA(FILE_PATH)) userData = await GUD(FILE_PATH)
            userData['zh'] = account;
            SUD(FILE_PATH, userData)
            return e.reply('账号绑定成功！');
        } catch (error) {
            return e.reply('绑定账号失败，请发送报错给主人:\r' + error)
        }
    }

    async bindPassword(e) {
        try {
            const [, , password] = e.msg.match(regular[1]);
            if (!password) return e.reply('请提供有效的密码。');
            const FILE_PATH = path.join(dataStorageDirectory, `${e.user_id}.json`);
            let userData = {}
            if (AAA(FILE_PATH)) userData = await GUD(FILE_PATH)
            userData['mi'] = password;
            SUD(FILE_PATH, userData)
            return e.reply('密码绑定成功！');
        } catch (error) {
            return e.reply('绑定密码失败，请发送报错给主人:\r' + error)
        }
    }

    async viewBindingInfo(e) {
        try {
            const FILE_PATH = path.join(dataStorageDirectory, `${e.user_id}.json`);
            if (!AAA(FILE_PATH)) return e.reply(tips[1]);
            const { zh, mi } = await GUD(FILE_PATH);

            if (!zh || !mi) return e.reply(tips[0])

            return e.reply(`你的zeep账号：${zh}\n你的zeep密码：${mi}`, false, { recallMsg: 5 });
        } catch (error) {
            return e.reply('查看失败，请发送报错给主人:\r' + error)
        }
    }

    async sb(e) {
        try {
            const FILE_PATH = path.join(dataStorageDirectory, `${e.user_id}.json`)
            if (!AAA(FILE_PATH)) return e.reply(tips[1])
            const { zh, mi } = await GUD(FILE_PATH)
            if (!zh || !mi) return e.reply(tips[0])
            const [, , , steps] = e.msg.match(regular[2])
            if (!steps) return e.reply('请提供有效的步数。')

            const url = "https://api.shuabu.net/StepApi/xm.php";
            const payload = new URLSearchParams({
                time: '1721667502',
                phone: zh,
                password: mi,
                step: steps,
                key: 'd68d768932e18b39b64cb9f4b79ce1d3'
            });

            const DATA = await (await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: payload.toString()
            })).json();

            const CODE = DATA['code']

            let back = ''
            if (CODE === 201) {
                back = DATA['msg']
            } else if (CODE === 200) {
                back = `同步成功！一共刷了${steps}步，快去炫耀吧`
            } else {
                back = `发生错误: ${DATA}`
            }
            return e.reply(back);
        } catch (error) {
            console.error('刷步失败:', error);
            e.reply('刷步失败，请稍后重试。');
        }
    }



    async sjsb(e) {
        try {
            const FILE_PATH = path.join(dataStorageDirectory, `${e.user_id}.json`);
            if (!AAA(FILE_PATH)) return e.reply(tips[1])
            const { zh, mi } = await GUD(FILE_PATH)
            if (!zh || !mi) return e.reply(tips[0])
            const [, , , maxStepsStr] = e.msg.match(regular[3])
            const maxSteps = Number(maxStepsStr);
            if (isNaN(maxSteps) || maxSteps <= 0) return e.reply('请提供有效的步数范围。')
            const steps = lodash.random(0, maxSteps)
            const url = "https://api.shuabu.net/StepApi/xm.php";
            const payload = new URLSearchParams({
                time: '1721667502',
                phone: zh,
                password: mi,
                step: steps,
                key: 'd68d768932e18b39b64cb9f4b79ce1d3'
            });

            const DATA = await (await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: payload.toString()
            })).json();

            const CODE = DATA['code']

            let back = ''
            if (CODE === 201) {
                back = DATA['msg']
            } else if (CODE === 200) {
                back = `同步成功！随机了${steps}步，快去炫耀吧`
            } else {
                back = `发生错误: ${DATA}`
            }
            return e.reply(back)
        } catch (error) {
            console.error('刷步失败:', error);
            e.reply('刷步失败，请稍后重试。');
        }
    }
}


/**
 * 全称GetUserData  
 * 即读取用户数据
 * @param {string} FILE_PATH 
 * @returns {JSON}
 */
async function GUD(FILE_PATH) {
    const DATA = await JSON.parse(fs.readFileSync(FILE_PATH, 'utf8'))
    return DATA
}

/**
 * 全称SaveUserData  
 * 即保存用户数据
 * @param {string} FILE_PATH 
 * @param {JSON} DATA 
 */
function SUD(FILE_PATH, DATA) {
    fs.writeFileSync(FILE_PATH, JSON.stringify(DATA, null, 4))
}

/**
 * 作用判断文件是否存在
 * @param {string} FILE_PATH 
 * @returns {Boolean}
 */
function AAA(FILE_PATH) {
    if (fs.existsSync(FILE_PATH)) return true
    return false
}